#!/bin/bash

bic_addr=0x20
busnum=9
maxRetries=10

# Retry a command with optional failover command
retry_command() {
    local command="$1"
    local maxRetries=${2:-10}
    local retryInterval=${3:-1}
    local failExecuteCmd=${4:-""}
    local retries=0

    while [ "$retries" -lt "$maxRetries" ]; do
        if bash -c "$command" >/dev/null 2>&1; then
            return 0
        else
            if [ -n "$failExecuteCmd" ]; then
                bash -c "$failExecuteCmd"
            fi

            retries=$((retries + 1))
            sleep "$retryInterval"
        fi
    done

    echo "[Error] Command failed after $maxRetries retries." >&2
    return 1
}

# Learn BIC Endpoint
learn_endpoint_cmd="busctl call au.com.codeconstruct.MCTP1 \
    /au/com/codeconstruct/mctp1/interfaces/mctpi2c${busnum} \
    au.com.codeconstruct.MCTP.BusOwner1 LearnEndpoint ay 1 ${bic_addr}"

if ! retry_command "$learn_endpoint_cmd" "$maxRetries" 1; then
    echo "[Error] Failed to learn BIC EID after $maxRetries attempts."
    exit 1
fi

exit 0
